package com.ztc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.define.State;
import com.ztc.util.GlobalUtil;
import com.ztc.util.UploadUtil;

@CrossOrigin
@Controller
public class UeditorController { 

	@RequestMapping("/config")
	public void config(HttpServletRequest request, HttpServletResponse response, String action, MultipartFile upfile)
			throws UnsupportedEncodingException, JSONException {
		response.setContentType("application/json");
//		response.setHeader("Content-Type" , "text/html");
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		try {
			String filePath = GlobalUtil.getGlobalParam("file.basepath");
			if(StringUtils.isNotBlank(filePath)) {
				rootPath = filePath;
//				System.out.println("config.properties-----rootPath:" + rootPath);
			}
			String exec = null;
			if ("uploadimage".equals(action) || "uploadvideo".equals(action)
					|| "uploadfile".equals(action)) { // 如果是上传图片、视频、和其他文件
//				State state = UploadUtil.upload(upfile, request, rootPath, action);
				State state = UploadUtil.uploadByFtp(upfile, request, rootPath, action);
				exec = state.toJSONString();
				String isSimpleUpload = request.getParameter("isSimpleUpload");
				if(StringUtils.isNotBlank(isSimpleUpload) && isSimpleUpload.equals("true")) {
					String clientServerPath = GlobalUtil.getGlobalParam("client.basepath");
					response.sendRedirect(clientServerPath + "/html/ueditorCallback.html?json=" + exec); //把json传递到客户端页面下面去呈现结果。
				}
			} else {
				ActionEnter actionEnter = new ActionEnter(request, rootPath);
				exec = actionEnter.exec();
			}

			PrintWriter writer = response.getWriter();
			writer.write(exec);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
